package com.menker.app.ui.generalweb;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.menker.app.Constants;
import com.menker.app.MyApp;
import com.menker.app.R;
import com.menker.app.biz.CurrentUser;
import com.menker.app.biz.WebPageInfo;
import com.menker.app.biz.WechatShareManager;
import com.menker.app.common.BaseWebViewToolbarActivity;
import com.menker.app.common.ToolbarOwner;
import com.menker.app.common.Utils;
import com.menker.app.di.DaggerScope;
import com.menker.app.di.Injector;
import com.menker.app.rest.ApiHelper;
import com.menker.app.rest.result.ShareInfo;
import com.menker.app.util.ShareUtils;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.res.StringRes;
import org.parceler.Parcels;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import myandroid.library.util.ApplicationHelper;

/**
 * @author J.Huang
 * @version 1.0
 */
@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(NoRefreshWebViewActivity.class)
@EActivity(R.layout.activity_no_refresh_webview)
public class NoRefreshWebViewActivity extends BaseWebViewToolbarActivity<GeneralWebViewView, GeneralWebViewPresenter>
        implements GeneralWebViewView {

    private static final int APP_PERMISSION = 100;
    private boolean permissionTip = true;

    @Inject
    ApiHelper mApiHelper;
    @Inject
    CurrentUser mCurrentUser;
    @Inject
    WechatShareManager mWechatShareManager;

    @StringRes(R.string.error_no_permission)
    String strErrNoPermission;
    @StringRes(R.string.error_no_internet)
    String strErrNoInternet;
    @StringRes(R.string.error_api)
    String strErrorApi;

    boolean mReloaded = false;

    String lastValidUrl = "";

    @AfterInject
    protected void initDI() {
        Injector.initNoRefreshWebViewActivityComponent().inject(this);
    }

    @AfterViews
    protected void initData() {
        ApplicationHelper.getInstance().addActivity(this);

        final WebPageInfo webPageInfo = Parcels.unwrap(getIntent().getParcelableExtra(WebPageInfo.EXTRA_NAME));

        if (webPageInfo == null) {
            return;
        }

        setupUI(this);
        // 刷新功能等
        initCustomUI();

        if (!webPageInfo.toolbarVisible && getSupportActionBar() != null) {
            getSupportActionBar().hide();
        } else {
            List<ToolbarOwner.MenuAction> menuActionList = new ArrayList<>();
//            if (!TextUtils.isEmpty(menuName)) {
//                ToolbarOwner.MenuAction menuAction = new ToolbarOwner.MenuAction(menuName, new Action0() {
//                    @Override
//                    public void call() {
//                    }
//                }, R.drawable.ic_add);
//
//                menuActionList.add(menuAction);
//            }

            ToolbarOwner.Config config = new ToolbarOwner.Config(webPageInfo.toolbarTitle, webPageInfo.toolbarUpButtonEnabled, menuActionList,
                    webPageInfo.toolbarTitleColor, webPageInfo.toolbarBgColor);
            mToolbarOwner.setConfig(config);
        }

        mWebViewManager.initJsBridge(mApiHelper, mCurrentUser);
        mWebViewManager.loadUrl(webPageInfo.url);

        ApplicationHelper.getInstance().addActivity(this);
    }

    @NonNull
    @Override
    public GeneralWebViewPresenter createPresenter() {
        return new GeneralWebViewPresenter(this);
    }

    @Override
    public void onResume() {
        mWebViewManager.onWebShow();
        super.onResume();
    }

    @Override
    public void onDestroy() {
        ApplicationHelper.getInstance().removeActivity(this);
        super.onDestroy();
    }

    /**
     * 重定义返回键操作
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (!Utils.UI.isFastDoubleClick()) {
//            if (!mWebViewManager.goBack()) {
            ApplicationHelper.getInstance().removeActivity(this);
//            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        }

        switch (resultCode) {
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions,grantResults);

        permissionTip = false;

        switch(requestCode)
        {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case APP_PERMISSION:
                boolean granted = true;
                for (int i : grantResults) {
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        granted = false;
                        break;
                    }
                }

                if(!granted) {
                    // 没有获取到权限，做特殊处理
                    Utils.UI.showToastLong(strErrNoPermission);
                    ApplicationHelper.getInstance().removeActivity(this);
                }
                break;
            default:
                break;
        }
    }

    @UiThread
    protected void reloadWebView() {
        if (mWebViewManager != null) {
            mWebViewManager.reload();
            mReloaded = true;
        }
    }

    public void loadUrl(String url) {
        mWebViewManager.loadUrl(url);
    }

    public void enableItemSharing(String itemId) {
        presenter.getShareInfo(itemId);
    }

    @UiThread
    @Override
    public void updateToolbar(final ShareInfo shareInfo) {
        if (!TextUtils.isEmpty(shareInfo.Price) && Float.valueOf(shareInfo.Price) > 0) {
            mToolbarTitle.setText(getString(R.string.share_text_money, shareInfo.Price));
        } else {
            mToolbarTitle.setText(R.string.share_text_no_money);
        }

        if (shareInfo.ShowShare) {
            ImageView imageView = (ImageView) findViewById(R.id.iv_toolbar_menu);
            imageView.setImageResource(R.drawable.ic_share);
            LinearLayout layout = (LinearLayout) findViewById(R.id.iv_toolbar_menu_layout);
            layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ShareUtils.showSharePanel(NoRefreshWebViewActivity.this, mWechatShareManager, shareInfo.ShareText, shareInfo.ShareText, shareInfo.ShareUrl, shareInfo.ShareIcon);

                    ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    clip.setPrimaryClip(ClipData.newPlainText(null, shareInfo.ShareText));

                    Utils.UI.showToastLong("内容已复制到剪贴板\n长按即可粘贴获取");
                }
            });
        }
    }
}
